<template>
  <div>
    <div v-if="activeData.table.rows">
      <el-divider>行标题</el-divider>
      <draggable :animation="340" :list="activeData.table.rows" group="selectItem" handle=".option-drag">
        <div v-for="(item, index) in activeData.table.rows" :key="index" class="select-item">
          <div class="select-line-icon option-drag">
            <i class="el-icon-s-operation" />
          </div>
          <el-input v-model="item.label" placeholder="选项名" size="small" />
          <div class="close-btn select-line-icon" @click="activeData.table.rows.splice(index, 1)">
            <i class="el-icon-remove-outline" />
          </div>
          <div class="close-btn select-line-icon" v-if="activeData.isSelectOrganization" @click="selectUser(item)">
            <el-button type="text">人员</el-button>
          </div>
          <div class="close-btn select-line-icon" v-if="activeData.isSelectOrganization" @click="selectDept(item)">
            <el-button type="text">部门</el-button>
          </div>
        </div>
      </draggable>
      <div style="margin-left: 20px; margin-bottom: 10px">
        <el-button
          icon="el-icon-circle-plus-outline"
          style="padding-bottom: 0"
          type="text"
          @click="addSelectItem(activeData.table.rows)"
        >
          添加选项
        </el-button>
        <el-button
          icon="el-icon-document-copy"
          style="padding-bottom: 0"
          type="text"
          @click="openBatchEditDialogHandle('rows')"
        >
          批量编辑
        </el-button>
      </div>
    </div>
    <div v-if="activeData.table.columns">
      <el-divider>列标题</el-divider>
      <draggable :animation="340" :list="activeData.table.columns" group="selectItem" handle=".option-drag">
        <div v-for="(item, index) in activeData.table.columns" :key="index" class="select-item">
          <div class="select-line-icon option-drag">
            <i class="el-icon-s-operation" />
          </div>
          <el-input v-model="item.label" placeholder="选项名" size="small" />
          <div class="close-btn select-line-icon" @click="activeData.table.columns.splice(index, 1)">
            <i class="el-icon-remove-outline" />
          </div>
          <el-checkbox v-model="item.canInput" v-if="matrixType === 'select'" title="允许填空"></el-checkbox>
        </div>
      </draggable>
      <div style="margin-left: 20px; margin-bottom: 10px">
        <el-button
          icon="el-icon-circle-plus-outline"
          style="padding-bottom: 0"
          type="text"
          @click="addSelectItem(activeData.table.columns)"
        >
          添加选项
        </el-button>
        <el-button
          icon="el-icon-document-copy"
          style="padding-bottom: 0"
          type="text"
          @click="openBatchEditDialogHandle('columns')"
        >
          批量编辑
        </el-button>
      </div>
    </div>
    <el-dialog title="批量编辑" :visible.sync="dialogVisible" width="30%">
      <span class="desc-text">每行对应一个选项</span>
      <el-input
        v-model="batchItemValue"
        type="textarea"
        :autosize="{ minRows: 20, maxRows: 5000 }"
        placeholder="选项1 选项2  选项3 "
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="batchEditSelectItems">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="userDialogVisible" title="人员选择" append-to-body>
      <el-tree
        ref="empTree"
        :accordion="true"
        :data="userData"
        :props="defaultProps"
        node-key="id"
        :default-expanded-keys="defaultShowNodes"
        show-checkbox
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span v-if="data.weight === 5">{{ node.label }}</span>
          <span v-if="data.weight === 6">{{ data.nickName }}({{ node.label }})</span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('user')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="deptDialogVisible" title="部门选择" width="30%" append-to-body>
      <el-tree ref="deptTree" :data="deptData" :props="defaultProps" default-expand-all show-checkbox />
      <span slot="footer" class="dialog-footer">
        <el-button @click="deptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('dept')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import _ from 'lodash'
import { getDeptTreeRequest, getEmpTreeRequest } from '@/formgen/src/api'

export default {
  name: 'MatrixOption',
  components: {
    draggable
  },
  props: ['activeData', 'matrixType'],
  data() {
    return {
      userData: [],
      deptData: [],
      batchItemValue: '',
      batchDataKey: '',
      defaultShowNodes: [], //默认展开第几级
      item: '',
      dialogVisible: false,
      userDialogVisible: false,
      deptDialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name',
        disabled: this.isDisabled
      }
    }
  },
  created() {},
  methods: {
    isDisabled(data, node) {
      //如果部门为空则不允许选择
      if (_.startsWith(data.id, 'dept') && data.children == null) {
        return true
      }
      return false
    },
    selectUser(item) {
      getEmpTreeRequest().then((res) => {
        this.userData = res.data
        //默认展开第一级
        this.defaultShowNodes.push(res.data[0].id)
      })
      this.item = item
      this.userDialogVisible = true
    },
    selectDept(item) {
      getDeptTreeRequest().then((res) => {
        this.deptData = res.data
      })
      this.item = item
      this.deptDialogVisible = true
    },
    addSelectItem(data) {
      data.push({
        id: new Date().getTime(),
        label: ''
      })
    },
    openBatchEditDialogHandle(key) {
      this.batchDataKey = key
      let data = this.activeData.table[key]
      this.batchItemValue = _.join(
        data.map((item) => item.label),
        '\n'
      )
      this.dialogVisible = true
    },
    async batchEditSelectItems() {
      const arrStrs = this.batchItemValue
      const arr = arrStrs.split('\n')
      // 获取原来的下标 避免导致id变化
      let oldData = this.activeData.table[this.batchDataKey]
      let labels = oldData.map((item) => item.label)
      if (arr.length > 0) {
        const options = []
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index]
          if (element.length > 0) {
            let oIndex = labels.indexOf(element)
            options.push({
              id: oIndex > -1 ? oldData[oIndex].id : new Date().getTime() + index,
              label: element
            })
          }
        }
        this.$set(this.activeData.table, this.batchDataKey, options)
        this.dialogVisible = false
      }
    },
    handleSubmit(param) {
      if ('user' == param) {
        this.changeValue = this.$refs.empTree.getCheckedNodes(true).map((item) => {
          return { name: item.name, nickName: item.nickName, id: item.id }
        })
        if (this.changeValue) {
          //选中的人员字符串
          this.item.label = this.changeValue.map((item) => item.nickName).join(',')
        }
        this.userDialogVisible = false
      }
      if ('dept' == param) {
        this.changeValue = this.$refs.deptTree.getCheckedNodes(true).map((item) => {
          return { name: item.name, id: item.id }
        })
        if (this.changeValue) {
          //选中的部门
          this.item.label = this.changeValue.map((item) => item.name).toString()
        }
        this.deptDialogVisible = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  align-items: center;

  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }

  & .el-input + .el-input {
    margin-left: 4px;
  }
}

.select-item + .select-item {
  margin-top: 4px;
}

.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}

.select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #777;
}

.option-drag {
  cursor: move;
}
</style>
